package com.vf.editor.mvc.system.login;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.SessionException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

import com.jfinal.aop.Before;
import com.jfinal.core.Path;
import com.jfinal.log.Log;
import com.vf.editor.common.controller.BaseController;
import com.vf.editor.common.plugins.shiro.ShiroKit;
import com.vf.editor.common.plugins.shiro.SimpleUser;

@Path(value = "/system/login", viewPath = "/")
public class LoginController extends BaseController {
	
	protected final Log LOG = Log.getLog(getClass());
	
	public void index() {
		Subject subject = ThreadContext.getSubject();
		if (subject.isAuthenticated()) {
			this.redirect("/index");
		} else {
			render("login.html");
		}
	}
	
	
	@Before({com.vf.editor.common.plugins.shiro.ShiroFormAuthenticationInterceptor.class})
	public void doLogin() {
		try {
			
		 	if(!validateCaptcha("captcha")) {
				this.renderError("验证码错误！");
				return;
			}
			
			UsernamePasswordToken token = getAttr("shiroToken");
			Subject subject = SecurityUtils.getSubject();
			ThreadContext.bind(subject);
			if (subject.isAuthenticated()) {
				subject.logout();
			} else {
				subject.login(token);
			}
			SimpleUser simpleUser =ShiroKit.getLoginUser();
			simpleUser.setSessionId(subject.getSession().getId().toString());
			this.renderSuccess("登录成功！",simpleUser);
        }catch (Exception e) {
        	this.renderError( e.getMessage());
        } 
	}
	
    public void logout() {
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
            this.removeSessionAttr("user");
            this.redirect("/system/login");
        } catch (SessionException ise) {
            LOG.debug("Encountered session exception during logout.  This can generally safely be ignored.", ise);
        } catch (Exception e) {
            LOG.debug("登出发生错误", e);
        }
    }
    
    public void captcha(){
        renderCaptcha();
    }
	
}
